import { ref, watch, onMounted } from "vue";
import { useStomp } from "@/composables/useStomp";
import { registerWebSocketInstance } from "@/plugins/websocket";
import { Auth } from "@/utils/auth";

export interface SystemStats {
  cpuUsage: number;
  cpuCores: number;
  memoryUsage: number;
  memoryUsed: number;
  memoryTotal: number;
  diskUsage: number;
  diskUsed: number;
  diskTotal: number;
  networkUpload: number;
  networkDownload: number;
  networkConnected: boolean;
  timestamp: number;
}

let globalInstance: ReturnType<typeof createSystemMonitorHook> | null = null;

function createSystemMonitorHook() {
  const systemStats = ref<SystemStats>({
    cpuUsage: 0,
    cpuCores: 0,
    memoryUsage: 0,
    memoryUsed: 0,
    memoryTotal: 0,
    diskUsage: 0,
    diskUsed: 0,
    diskTotal: 0,
    networkUpload: 0,
    networkDownload: 0,
    networkConnected: false,
    timestamp: 0,
  });

  const isConnected = ref(false);
  const isConnecting = ref(false);
  const errorMessage = ref("");

  const stompInstance = useStomp({
    reconnectDelay: 15000,
    maxReconnectAttempts: 3,
    connectionTimeout: 10000,
    useExponentialBackoff: true,
    url: import.meta.env.VITE_APP_WS_ENDPOINT,
  });

  const {
    connect,
    subscribe,
    unsubscribe,
    disconnect,
    isConnected: stompConnected,
  } = stompInstance;

  registerWebSocketInstance("systemMonitor", stompInstance);

  let subscriptionId = "";
  let retryTimer: NodeJS.Timeout | null = null;

  const subscribeToSystemStats = () => {
    if (retryTimer) {
      clearTimeout(retryTimer);
      retryTimer = null;
    }

    if (!stompConnected.value) {
      retryTimer = setTimeout(subscribeToSystemStats, 5000);
      return;
    }

    if (subscriptionId) {
      unsubscribe(subscriptionId);
    }

    subscriptionId = subscribe("/topic/system-stats", (message: any) => {
      try {
        const data: SystemStats = JSON.parse(message.body);
        systemStats.value = { ...systemStats.value, ...data };
      } catch (e) {
        console.error("[SystemMonitor] 解析系统数据失败:", e);
        errorMessage.value = "数据解析错误，请稍后重试";
      }
    });
  };

  const initWebSocket = () => {
    if (isConnecting.value || isConnected.value) return;

    const token = Auth.getAccessToken();
    if (!token) {
      errorMessage.value = "未检测到认证信息，无法连接";
      return;
    }

    isConnecting.value = true;
    connect();
  };

  const closeWebSocket = () => {
    if (subscriptionId) {
      unsubscribe(subscriptionId);
      subscriptionId = "";
    }
    if (retryTimer) {
      clearTimeout(retryTimer);
      retryTimer = null;
    }
    disconnect();
    isConnected.value = false;
    isConnecting.value = false;
  };

  watch(stompConnected, (connected) => {
    if (connected) {
      isConnected.value = true;
      isConnecting.value = false;
      errorMessage.value = "";
      subscribeToSystemStats();
      console.log("[SystemMonitor] 系统监控 WebSocket 连接成功");
    } else if (!isConnecting.value) {
      isConnected.value = false;
      errorMessage.value = "系统监控连接已断开，正在重试...";
    }
  });

  // 添加组件挂载时初始化 WebSocket 连接的逻辑
  onMounted(() => {
    if (!isConnected.value && !isConnecting.value) {
      initWebSocket();
    }
  });

  return {
    systemStats,
    isConnected,
    isConnecting,
    errorMessage,
    initWebSocket,
    closeWebSocket,
  };
}

export function useSystemMonitor() {
  if (!globalInstance) {
    globalInstance = createSystemMonitorHook();
  }
  return globalInstance;
}
